package main

import (
	"fmt"
	"unsafe"
)

// 16 | 非类型安全：让你既爱又恨的 unsafe
func main() {

	i := 10
	ip := &i
	var fp *float64 = (*float64)(unsafe.Pointer(ip))
	*fp = *fp * 3
	fmt.Println(i)

	p := new(person)
	// Name是person的第一个字段不用偏移，即可通过指针修改
	pName := (*string)(unsafe.Pointer(p))
	*pName = "靖哥哥"
	// Age并不是person的第一个字段，所以需要进行偏移，这样才能正确定位到Age字段这块内存，才可以正确的修改
	pAge := (*int)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + unsafe.Offsetof(p.Age)))
	*pAge = 20
	fmt.Println(*p)

	// 通过 Sizeof 函数你可以查看任何类型（比如字符串、切片、整型）占用的内存大小
	fmt.Println(unsafe.Sizeof(true))
	fmt.Println(unsafe.Sizeof(int8(0)))
	fmt.Println(unsafe.Sizeof(int16(10)))
	fmt.Println(unsafe.Sizeof(int32(10000000)))
	fmt.Println(unsafe.Sizeof(int64(10000000000000)))
	fmt.Println(unsafe.Sizeof(int(10000000000000000)))
	fmt.Println(unsafe.Sizeof(string("靖哥哥")))
	fmt.Println(unsafe.Sizeof([]string{"靖哥哥", "曹靖"}))
}

type person struct {
	Name string
	Age  int
}
